package logic

import (
	"book-hub/cache"
	"context"
	"fmt"
	"math/rand"
	"time"

	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SenSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSenSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SenSmsLogic {
	return &SenSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SenSmsLogic) SenSms(in *bookrpc.SenSmsRequest) (*bookrpc.SenSmsResponse, error) {
	// todo: add your logic here and delete this line
	i := rand.Intn(9000) + 1000
	result, _ := cache.Rdb.Get(cache.Ctx, "semsmsSum"+in.Mobile).Int()
	if result >= 1 {
		return nil, fmt.Errorf("一分钟只允许发送一次")
	}
	//sms, err := pkg.SenSms(in.Mobile, strconv.Itoa(i))
	//if err != nil {
	//	return nil, err
	//}
	//if sms.Code != 2 {
	//	return nil, fmt.Errorf(sms.Msg)
	//}
	cache.Rdb.Set(cache.Ctx, "sensms"+in.Mobile, i, time.Minute*5)
	cache.Rdb.Incr(cache.Ctx, "semsmsSum"+in.Mobile)
	cache.Rdb.Expire(cache.Ctx, "semsmsSum"+in.Mobile, time.Minute*1)
	return &bookrpc.SenSmsResponse{}, nil
}
